//
//  CarouselView.m
//  Carousel
//
//  Created by dllo on 16/1/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CarouselView.h"
#import "CarouselCollectionViewCell.h"
#import "UIImageView+WebCache.h"

@interface CarouselView ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, retain) UICollectionView *collectionV;
@property (nonatomic, retain) UIPageControl *pageC;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, assign) NSInteger PrePage;

@end


@implementation CarouselView

//重写set方法
- (void)setPicArr:(NSArray *)picArr
{
    if (_picArr != picArr) {
        [_picArr release];
        _picArr = [picArr retain];
    }
    [self.collectionV reloadData];
    [self createPageController];
}

- (void)dealloc
{
    [_picArr release];
    [_pageC release];
    [_collectionV release];
    [_timer release];
    [super dealloc];
}

+ (instancetype)carouselViewWithFrame:(CGRect)frame
{
    CarouselView *carouselV = [[[CarouselView alloc] initWithFrame:frame] autorelease];
    
    return carouselV;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.PrePage = 1;
        [self createCollectionView];
        
    }
    return self;
}

- (void)createCollectionView
{
    
    UICollectionViewFlowLayout *flowL = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    // 单元大小
    flowL.itemSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
    flowL.minimumLineSpacing = 0;
    flowL.minimumInteritemSpacing = 0;
    // 滚动方向
    flowL.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) collectionViewLayout:flowL];
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    self.collectionV.contentOffset = CGPointMake(self.bounds.size.width, 0);
    self.collectionV.pagingEnabled = YES;
    self.collectionV.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.collectionV];
    [_collectionV release];
    
    // 注册自定义cell
    [self.collectionV registerClass:[CarouselCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self addNSTimer];
    
}

#pragma 加定时
- (void)addNSTimer
{
    //创建一个NSTimer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.f target:self selector:@selector(nextpage) userInfo:nil repeats:YES];
    //添加到主运行程序事件中
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}
#pragma 删除时间
- (void)removeNSTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

// item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.picArr.count + 2;
}
// cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CarouselCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (0 == indexPath.row) {
        NSString *imageUrl = [self.picArr lastObject];
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"clamdown"]];
        return cell;
    } else if (self.picArr.count + 1 == indexPath.row) {
        NSString *imageUrl = [self.picArr firstObject];
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"clamdown"]];
        return cell;
    } else {
        NSString *imageUrl = [self.picArr objectAtIndex:indexPath.row - 1];
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"clamdown"]];
        return cell;
    }
    
    
}

#pragma 下一页
- (void)nextpage
{
    if (nil != self.picArr) {
        //1获取当前正在展示的位置
        NSIndexPath *currentIndexPath = [[self.collectionV indexPathsForVisibleItems]lastObject];
        
        //马上显示回最中间那组的数据
        NSIndexPath *currentIndexPathRest = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:0];
        [self.collectionV scrollToItemAtIndexPath:currentIndexPathRest atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        
        //2计算出下一个需要展示的位置
        static  NSInteger nextItem = 0;
        if (self.picArr.count + 1 != currentIndexPathRest.item) {
            nextItem = currentIndexPathRest.item + 1;
        } else {
            self.collectionV.contentOffset = CGPointMake(self.bounds.size.width, 0);
            nextItem = 1;
        }
        
        self.pageC.currentPage = nextItem - 1;
        
        NSIndexPath *nextIndexPath=[NSIndexPath indexPathForItem:nextItem inSection:0];
        
        //3通过动画滚动到下一个位置
        [self.collectionV scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        
    }
    
}
#pragma 当拖动的时候时间停止
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    [self removeNSTimer];
}
#pragma 当停止拖动的时候时间开始
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addNSTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.collectionV == scrollView) {
        
        NSInteger currentPage = scrollView.contentOffset.x / self.bounds.size.width;
        if (0 == currentPage) {
            scrollView.contentOffset = CGPointMake(self.bounds.size.width * self.picArr.count, 0);
            currentPage = self.picArr.count;
        }
        if (self.picArr.count + 1 == currentPage) {
            scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
            currentPage = 1;
        }
        
        // 判断当前页码与上一页码是否相等
        if (currentPage != self.PrePage) {
            
            
            self.pageC.currentPage = currentPage - 1;
            
            // 更新之前页码
            self.PrePage = currentPage;
            
        }

    }
}

#pragma mark - 创建pageControl
- (void)createPageController {
    self.pageC = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 30, self.bounds.size.width, 30)];
    NSLog(@"%ld",self.picArr.count);
    self.pageC.numberOfPages = self.picArr.count;
    self.pageC.userInteractionEnabled = NO;
    [self addSubview:self.pageC];
    [self.pageC release];
}


@end
